package src.com.neusoft.nep.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import src.com.neusoft.nep.common.AQI;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.ProvidedData;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

public class AQIDistributeTendController {
    @FXML
    TableView<Map<String, String>> tableView;
    @FXML
    TableColumn<Map<String, String>, String> colNumber, colMonth, colOver;
    @FXML
    Button btn_date;

    private ObservableList<Map<String, String>> tableList = FXCollections.observableArrayList();
    private AQI aqiAnalyzer = new AQI();
    private Map<String, ProvidedData> dataMap; // 存储读取的数据
    private final DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
    private Stage loginViewStage;

    public void setLoginViewStage(Stage stage) {
        this.loginViewStage = stage;
    }

    public void initialize() {
        // 设置表格列值工厂
        setupTableColumns();

        // 加载数据
        loadData();
    }

    private void setupTableColumns() {
        colNumber.setCellValueFactory(cellData -> {
            int index = cellData.getTableView().getItems().indexOf(cellData.getValue()) + 1;
            return new SimpleStringProperty(String.valueOf(index));
        });
        colMonth.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().get("month")));
        colOver.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().get("overCount")));
    }

    private void loadData() {
        try {
            // 从文件读取数据
            dataMap = FileUtils.readMapObject("AdminData.txt");

            if (dataMap == null || dataMap.isEmpty()) {
                throw new RuntimeException("数据文件为空或读取失败");
            }

            // 分析数据并加载到表格
            analyzeAndLoadData();

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("加载数据失败: " + e.getMessage());
        }
    }

    private void analyzeAndLoadData() {
        // 清空现有数据
        tableList.clear();

        // 统计每月超标次数
        Map<String, Integer> monthlyOverCounts = new HashMap<>();

        // 遍历所有数据，统计每月超标情况
        for (ProvidedData data : dataMap.values()) {
            LocalDate date = LocalDate.parse(data.getDate());
            String monthKey = date.format(monthFormatter);

            // 计算污染物等级
            double so2 = Double.parseDouble(data.getSo2());
            double co = Double.parseDouble(data.getCo());
            double pm = Double.parseDouble(data.getPm());

            int so2Level = aqiAnalyzer.getLevel(so2, "so2");
            int coLevel = aqiAnalyzer.getLevel(co, "co");
            int pmLevel = aqiAnalyzer.getLevel(pm, "pm");

            // AQI等级取各污染物等级的最大值
            int aqiLevel = Math.max(Math.max(so2Level, coLevel), pmLevel);

            // 只要AQI等级>=3，该日算作超标
            if (aqiLevel >= 3) {
                monthlyOverCounts.put(monthKey, monthlyOverCounts.getOrDefault(monthKey, 0) + 1);
            }
        }

        // 将统计结果转换为表格数据（按月份排序）
        List<String> sortedMonths = new ArrayList<>(monthlyOverCounts.keySet());
        sortedMonths.sort(Comparator.naturalOrder()); // 确保按年月顺序排列

        for (String month : sortedMonths) {
            Map<String, String> row = new HashMap<>();
            row.put("month", month);
            row.put("overCount", String.valueOf(monthlyOverCounts.get(month)));
            tableList.add(row);
        }

        // 设置表格数据
        tableView.setItems(tableList);
    }

    // 打开新窗口
    public void date() throws IOException {
        Stage stage = new Stage();
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../view/AQIDateStatisticsView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        AQIDateDistributeTendController controller = fxmlLoader.getController();
        controller.setLoginViewStage(stage);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.showAndWait();
    }
}